var Game = new function() {
    this.initialize = function(canvasElementId, sprite_data, callback) {
        this.canvas = document.getElementById(canvasElementId);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        // Set up the rendering context
        this.ctx = this.canvas.getContext && this.canvas.getContext('2d');
        if (!this.ctx) {
            return alert("Please upgrade your browser to play");
        }
        // Set up input
        this.setupInput();
        // Start the game loop
        this.loop();
        // Load the sprite sheet and pass forward the callback.
        SpriteSheet.load(sprite_data, callback);
    };

    // Handle Input
    var KEY_CODES = {
        37: 'left',
        39: 'right',
        32: 'fire'
    };
    this.keys = {};
    this.setupInput = function() {
        window.addEventListener('keydown', function(event) {
            if (KEY_CODES[event.keyCode]) {
                //establece por ejemplo keys["left"] = true
                Game.keys[KEY_CODES[event.keyCode]] = true;
                event.preventDefault();
            }
        }, false);
        window.addEventListener('keyup', function(event) {
            if (KEY_CODES[event.keyCode]) {
                Game.keys[KEY_CODES[event.keyCode]] = false;
                //previene acciones x default del browser
                event.preventDefault();
            }
        }, false);
    };

    // Game Loop
    var boards = [];

    this.loop = function() {
        //los tableros se actualizan cada 30 milesimas de segundo
        var t = 30;
        var dt = t / 1000;

        //se verifica cada tablero y se indica que debe transcurrir tiempo
        for (var i = 0, len = boards.length; i < len; i++) {
            if (boards[i]) {
                boards[i].step(dt);
                boards[i].draw(Game.ctx);
            }
        }

        setTimeout(Game.loop, t);
    };

    // Change an active game board
    this.setBoard = function(num, board) {
        boards[num] = board;
    };
};



/*al indicar = new function se indica que se cree una unica instancia de SpriteSheet
 */
var SpriteSheet = new function() {
    this.map = {};

    this.load = function(spriteData, callback) {
        this.map = spriteData;
        this.image = new Image();
        this.image.onload = callback;
        this.image.src = 'images/sprites.png';
    };

    this.draw = function(ctx, sprite, x, y, frame) {
        var s = this.map[sprite];
        if (!frame) frame = 0;
        ctx.drawImage(this.image,
            s.sx + frame * s.w,
            s.sy,
            s.w, s.h,
            Math.floor(x), Math.floor(y),
            s.w, s.h);
    };
}
